
MAIN_SELELECTBOX_ID = "#id_owner";
SUB_SELECTBOX_ID = "#id_project_code";
URL_TO_LOAD_DATA = "/report/utils/project_codes_per_owner/";

/*
 *
 * Select option with id used in callback of ajaxAddOption
 * args - array of arguments to pass onto the functon
 */
function selectID(args){
        $(SUB_SELECTBOX_ID).selectOptions(args[0].id);      
}

/*
 * addOptionsJSON(url, id_main)
 * Add options from server side (getJSON is used)
 *
 */

function addOptionsJSON(url, id_main, id_sub){
    $.getJSON(url + id_main + "/", function(data){
	if(data != null){ 
	options = '<option value="" selected="selected">---------</option>';     
	for (var i = 0; i < data.options.length; i++) {
		try
		{
			options += '<option value="' + data.options[i].selectValue + '">' + data.options[i].selectDisplay + '</option>';
		} catch (error){}	
	}
	$(SUB_SELECTBOX_ID).html(options);
	selectID([{"id": id_sub}]);
	}
    });
}

/*
 *
 * loadOptions(mainSelectID, subSelectID)
 * add options via AJAX 
 * @param mainSelectID - string  for getting selected values from mainSelect
 * @param subSelectID - string for getting selected values in subSelect to change selected 
 */
function projectCodeLoadOptions(mainSelectID, subSelectID){
        var id_main = $(mainSelectID).selectedValues()[0];
        var id_sub = $(subSelectID).selectedValues()[0];
    
    
	
    	$(subSelectID).removeOption(/./);
	addOptionsJSON(URL_TO_LOAD_DATA, id_main, id_sub)
        //$(subSelectID).ajaxAddOption(URL_TO_LOAD_DATA + id_main + "/", {}, false, selectID, [{"id": id_sub}]);
}

$(document).ready(
    function() {
		if($(MAIN_SELELECTBOX_ID)){
               		var t=setTimeout("projectCodeLoadOptions(MAIN_SELELECTBOX_ID, SUB_SELECTBOX_ID)", 1000);
        		$(MAIN_SELELECTBOX_ID).bind("change", function(e){
                        	projectCodeLoadOptions(MAIN_SELELECTBOX_ID, SUB_SELECTBOX_ID);
               	 	});
		}
        
        }
);
